package com.kevin.ymqquan.activity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;

import com.kevin.ymqquan.R;
import com.kevin.ymqquan.bean.PayTypeList;
import com.kevin.ymqquan.constants.Constants;
import com.kevin.ymqquan.custom.CustomToast;
import com.kevin.ymqquan.httppost.HttpPostService;

public class CoursePayDetailActivity extends Activity implements
		OnItemSelectedListener {

	private ImageView iv_pay_detail_back;

	private String courseId;
	private String userId;

	private EditText et_activeapply_starttime;

	private List<String> infoList = new ArrayList<String>();

	private List<PayTypeList> payTypeList = new ArrayList<PayTypeList>();
	private Spinner sp_payType;
	private ArrayAdapter<String> adapter;

	private int timeFlag;
	private int mYear;
	private int mMonth;
	private int mDay;

	private int days;
	private int months;

	private Dialog dialog;

	private String type;
	private String payId;

	private Button btn_pay_apply_submit;

	private EditText et_activeapply_endtime;
	private EditText et_activeapply_months;
	private EditText et_activeapply_days;
	private EditText et_activeapply_times;
	private EditText et_activeapply_money;
	private EditText et_activeapply_remark;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_clubuser_pay);

		Intent i = getIntent();
		courseId = i.getStringExtra("courseId");
		userId = i.getStringExtra("userId");
		init();

		PayTypeReasonAsyTask payask = new PayTypeReasonAsyTask();
		payask.execute();
	}

	private void init() {
		// TODO Auto-generated method stub

		btn_pay_apply_submit = (Button) findViewById(R.id.btn_pay_apply_submit);
		btn_pay_apply_submit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
//				btn_pay_apply_submit.setEnabled(false);
				if ("1".equals(type) || "2".equals(type)) {
					if ("".equals(et_activeapply_endtime.getText().toString())
							|| "".equals(et_activeapply_starttime.getText()
									.toString())) {
						CustomToast.CustomActivityToast(CoursePayDetailActivity.this,
								"时间不能为空", 0);
					} else {
						PayApplyReasonAsyTask payApply = new PayApplyReasonAsyTask();
						payApply.execute();
					}
				} else {

					if ("".equals(et_activeapply_money.getText().toString())) {
						CustomToast.CustomActivityToast(CoursePayDetailActivity.this,
								"金额不能为空", 0);
					} else {
						PayApplyReasonAsyTask payApply = new PayApplyReasonAsyTask();
						payApply.execute();
					}
				}
			}
		});
		et_activeapply_endtime = (EditText) findViewById(R.id.et_activeapply_endtime);
		et_activeapply_months = (EditText) findViewById(R.id.et_activeapply_months);
		et_activeapply_days = (EditText) findViewById(R.id.et_activeapply_days);
		et_activeapply_times = (EditText) findViewById(R.id.et_activeapply_times);
		et_activeapply_remark = (EditText) findViewById(R.id.et_paydetail_remark);
		et_activeapply_money = (EditText) findViewById(R.id.et_activeapply_money);

		et_activeapply_starttime = (EditText) findViewById(R.id.et_activeapply_starttime);

		et_activeapply_starttime.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				timeFlag = 0;
				showDialog(0);
			}
		});

		et_activeapply_starttime
				.setOnFocusChangeListener(new OnFocusChangeListener() {
					public void onFocusChange(View v, boolean hasFocus) {
						if (hasFocus == true) {
							timeFlag = 0;
							hideIM(v);
							showDialog(0);
						}
					}
				});
		iv_pay_detail_back = (ImageView) findViewById(R.id.iv_pay_detail_back);
		iv_pay_detail_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				CoursePayDetailActivity.this.finish();
			}
		});
		sp_payType = (Spinner) findViewById(R.id.spinner_paytype);

	}

	class PayTypeReasonAsyTask extends AsyncTask<String, Object, String> {

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub

			String param = "{\"method\":\"coursePayType\",\"courseId\":\"" + courseId
					+ "\"}";
			String replyList = "";
			try {
				replyList = HttpPostService.PostJsonString(
						Constants.ServerAddr, param);
			} catch (Exception e) {
				e.printStackTrace();
			}
			// Log.i("kevinlog", param);
			// Log.i("kevinlog", replyList);
			return replyList;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			// Log.i("kevinlog", result);
			JSONObject jsonObject;
			try {
				jsonObject = new JSONObject(result);
				String resultType = jsonObject.getString("status");
				if ("0".equals(resultType)) {
					JSONArray jsonArray = jsonObject
							.getJSONArray("payTypeList");
					for (int i = 0; i < jsonArray.length(); i++) {
						JSONObject eduPolicyObject = jsonArray.getJSONObject(i);
						PayTypeList list = new PayTypeList();
						list.setPayId(Integer.parseInt(eduPolicyObject
								.getString("payId")));
						list.setConsume(eduPolicyObject.getString("consume"));
						list.setDays(eduPolicyObject.getString("days"));
						list.setMonths(eduPolicyObject.getString("months"));
						list.setPayName(eduPolicyObject.getString("payName"));
						list.setRemark(eduPolicyObject.getString("remark"));
						list.setTimes(eduPolicyObject.getString("times"));
						list.setType(eduPolicyObject.getString("type"));
						payTypeList.add(list);
						infoList.add(eduPolicyObject.getString("payName"));
					}

					adapter = new ArrayAdapter<String>(CoursePayDetailActivity.this,
							R.layout.free_spinner_text, infoList);
					adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					sp_payType.setAdapter(adapter);

					sp_payType
							.setOnItemSelectedListener(CoursePayDetailActivity.this);

				} else if ("100".equals(resultType)) {
					CustomToast.CustomActivityToast(CoursePayDetailActivity.this,
							"服务器异常，请稍后重试", 0);
				}

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				// Log.i("kevinlog", "error");
				e.printStackTrace();
			}
			//
			// dialog.dismiss();
		}

	}

	class PayApplyReasonAsyTask extends AsyncTask<String, Object, String> {

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub

			int times = "不限".equals(et_activeapply_times.getText().toString()) ? 0
					: Integer.parseInt(et_activeapply_times.getText()
							.toString());
			String param = "{\"method\":\"userCPay\",\"userId\":\"" + userId
					+ "\",\"courseId\":\"" + courseId + "\",\"consume\":\""
					+ et_activeapply_money.getText().toString()
					+ "\",\"startDate\":\""
					+ et_activeapply_starttime.getText().toString()
					+ "\",\"endDate\":\""
					+ et_activeapply_endtime.getText().toString()
					+ "\",\"times\":\"" + times + "\",\"type\":\"" + type
					+ "\",\"payId\":\"" + payId + "\",\"remark\":\""
					+ et_activeapply_remark.getText().toString() + "\"}";
			String replyList = "";
			try {
				replyList = HttpPostService.PostJsonString(
						Constants.ServerAddr, param);
			} catch (Exception e) {
				e.printStackTrace();
			}
			Log.i("kevinlog", param);
			Log.i("kevinlog", replyList);
			return replyList;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			// Log.i("kevinlog", result);
			JSONObject jsonObject;
			try {
				jsonObject = new JSONObject(result);
				String resultType = jsonObject.getString("status");
				if ("0".equals(resultType)) {
					CustomToast.CustomActivityToast(CoursePayDetailActivity.this,
							"缴费成功", 0);
					CoursePayDetailActivity.this.finish();
				} else if ("100".equals(resultType)) {
					CustomToast.CustomActivityToast(CoursePayDetailActivity.this,
							"服务器异常，请稍后重试", 0);
					btn_pay_apply_submit.setEnabled(true);
				} else if ("200".equals(resultType)) {
					CustomToast.CustomActivityToast(CoursePayDetailActivity.this,
							"缴费时间冲突", 0);
					btn_pay_apply_submit.setEnabled(true);
				} 

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				Log.i("kevinlog", "error");
				e.printStackTrace();
			}

			// dialog.dismiss();
		}

	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		// TODO Auto-generated method stub
		// private EditText et_activeapply_endtime;
		// private EditText et_activeapply_months;
		// private EditText et_activeapply_days;
		// private EditText et_activeapply_times;
		// private EditText et_activeapply_money;
		// private EditText et_activeapply_remark;
		// Log.i("kevinlog", arg2+"");
		// if (arg2 == 0) {
		// userSex = "";
		// } else {
		// userSex = arg2 + "";
		// }
		//
		// onRefresh();

		type = payTypeList.get(arg2).getType();
		payId = payTypeList.get(arg2).getPayId() + "";
		if (!"不限".equals(payTypeList.get(arg2).getDays())) {
			days = Integer.parseInt(payTypeList.get(arg2).getDays());
		}

		if (!"不限".equals(payTypeList.get(arg2).getMonths())) {
			months = Integer.parseInt(payTypeList.get(arg2).getMonths());
			days = -1;
		}

		et_activeapply_months.setText(payTypeList.get(arg2).getMonths());
		et_activeapply_days.setText(payTypeList.get(arg2).getDays());
		et_activeapply_times.setText(payTypeList.get(arg2).getTimes());
		et_activeapply_remark.setText(payTypeList.get(arg2).getRemark());

		if ("1".equals(payTypeList.get(arg2).getType())
				|| "2".equals(payTypeList.get(arg2).getType())) {
			et_activeapply_money.setText(payTypeList.get(arg2).getConsume());
			// et_activeapply_endtime.setEnabled(true);
			et_activeapply_starttime.setEnabled(true);
			et_activeapply_money.setEnabled(false);
			et_activeapply_endtime.setText("");
			et_activeapply_starttime.setText("");
		} else {
			et_activeapply_money.setText("");
			et_activeapply_money.setEnabled(true);
			et_activeapply_endtime.setHint("不可用");
			et_activeapply_starttime.setHint("不可用");
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
		Log.i("kevinlog", "onNothingSelected");

	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			String mm;
			String dd;
			if (monthOfYear <= 9) {
				mMonth = monthOfYear + 1;
				mm = "0" + mMonth;
			} else {
				mMonth = monthOfYear + 1;
				mm = String.valueOf(mMonth);
			}
			if (dayOfMonth <= 9) {
				mDay = dayOfMonth;
				dd = "0" + mDay;
			} else {
				mDay = dayOfMonth;
				dd = String.valueOf(mDay);
			}
			mDay = dayOfMonth;
			if (timeFlag == 0) {
				et_activeapply_starttime.setText(String.valueOf(mYear) + "-"
						+ mm + "-" + dd);
				try {
					Date d = new SimpleDateFormat("yyyy-MM-dd").parse(String
							.valueOf(mYear) + "-" + mm + "-" + dd);

					GregorianCalendar gc = new GregorianCalendar();
					SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
					gc.setTime(d);
					gc.add(2, months);
					gc.add(5, days);
					gc.set(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH),
							gc.get(Calendar.DATE));
					et_activeapply_endtime.setText(sf.format(gc.getTime()));
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				// et_activeapply_endtime.setText(text);
			} else {
				et_activeapply_starttime.setText(String.valueOf(mYear) + "-"
						+ mm + "-" + dd);
			}
		}
	};

	protected Dialog onCreateDialog(int id) {

		Calendar cal = Calendar.getInstance();
		mDay = cal.get(Calendar.DATE);
		mMonth = cal.get(Calendar.MONTH);
		mYear = cal.get(Calendar.YEAR);
		switch (id) {
		case 0:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		case 1:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		}
		return null;
	}

	// 隐藏手机键盘
	private void hideIM(View edt) {
		try {
			InputMethodManager im = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
			IBinder windowToken = edt.getWindowToken();
			if (windowToken != null) {
				im.hideSoftInputFromWindow(windowToken, 0);
			}
		} catch (Exception e) {

		}
	}
}
